package one.stand.controller;

import com.jmp.api.crm.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.CompanyDissolutionRequest;
import com.jmp.base.dto.CompanyEditRequest;
import com.jmp.base.dto.CompanyTransferRequest;
import com.jmp.feign.CompanyFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.ConvertUtils;
import one.stand.mapper.GoodsApiCrmPcMapper;
import one.stand.model.Company;
import one.stand.model.CompanyShowroom;
import one.stand.model.GoodsType;
import one.stand.model.ResultModel;
import one.stand.request.CompanyAccountRequest;
import one.stand.request.GoodSpecRequest;
import one.stand.request.GoodsRequest;
import one.stand.response.IndustryResponse;
import one.stand.service.CompanyBaseService;
import one.stand.service.CompanyShowroomService;
import one.stand.util.AssertUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.List;

/**
 * @author: ZRH
 * @CreateDate: 2019/4/17 9:45
 */
@RestController
@RequestMapping("crmPc/companyGoods")
@Api(description = "crm-PC企业管理(产品管理)")
public class CompanyController extends BaseController {
    @Autowired
    private CompanyFeign companyFeign;

    @Autowired
    private GoodsApiCrmPcMapper goodsApiCrmPcMapper;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private CompanyShowroomService companyShowroomService;

    @ApiOperation(value = "查询所有二级分类（用于商品分类下拉列表）")
    @PostMapping("/getGoodsTypeInfo")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<GoodsTypeSelectResponse>> getGoodsTypeInfo(@RequestAttribute GoodsTypeSelectRequest request) {

        List<GoodsType> list = goodsApiCrmPcMapper.selectSelectTypeList(request.getCId(), false);

        List<GoodsTypeSelectResponse> responseList = ConvertUtils.list(list, type -> GoodsTypeSelectResponse.builder()
                .goodstypeId(type.getGoodstypeId())
                .name(type.getName())
                .parentId(type.getParentId())
                .groupName(type.getGroupName())
                .build());

        return ResultModel.success(responseList);
    }

    @ApiOperation(value = "查询简单商品分类（用于商品分类下拉列表）")
    @PostMapping("/type/parent")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<GoodsTypeParentResponse> getGoodsTypeParent(@RequestAttribute GoodsTypeParentRequest request) {

        List<GoodsType> list = goodsApiCrmPcMapper.selectParent(request.getCId());

        List<GoodsTypeParentResponse.Type> types = ConvertUtils.list(list, type -> GoodsTypeParentResponse.Type.builder()
                .id(type.getGoodstypeId())
                .name(type.getGroupName())
                .build());

        GoodsTypeParentResponse response = GoodsTypeParentResponse.builder()
                .types(types)
                .build();
        return ResultModel.success(response);
    }

    @PostMapping("/moveGoodsInfo")
    @ApiOperation(value = "上移/下移商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品id", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "type", value = "1上移，2下移", required = true, paramType = "Integer"),
    })
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<Boolean> moveGoodsInfo(@RequestAttribute GoodsRequest request) {
        return crmFegin.moveGoodsInfo(request);
    }

    @PostMapping("/addGoodSpecInfo")
    @ApiOperation(value = "添加商品规格信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "specName", value = "类型名称", required = true, paramType = "String"),
            @ApiImplicitParam(name = "specAttribute", value = "属性名", required = true, paramType = "String"),
            @ApiImplicitParam(name = "specNum", value = "库存", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "price", value = "价格(分)", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "parentId", value = "父级id（如果是类型的第一个属性就给0，如果不是就给第一个属性的specId）", required = true, paramType = "Integer"),
    })
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel addGoodSpecInfo(@RequestAttribute GoodSpecRequest request) {

        return crmFegin.addGoodSpecInfo(request);
    }

    @ApiOperation(value = "转移产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "goodstypeId", value = "商品类型ID", required = true, paramType = "Integer"),
    })
    @PostMapping("/transferGoods")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel transferGoods(@RequestAttribute GoodsRequest request) {

        return crmFegin.transferGoods(request);
    }

    @PostMapping("/delGoodsInfo")
    @ApiOperation(value = "删除商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品id", required = true, paramType = "Integer"),
    })
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel delGoodsInfo(@RequestAttribute GoodsRequest request) {

        return crmFegin.delGoodsInfo(request);
    }

    @ApiOperation(value = "删除商品规格信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "specId", value = "商品分类id", required = true, paramType = "Integer"),
    })
    @PostMapping("/delGoodSpecInfo")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel delGoodSpecInfo(@RequestAttribute GoodSpecRequest request) {

        return crmFegin.delGoodSpecInfo(request);
    }

    @ApiOperation(value = "个人企业信息")
    @SecurityAuthCheck(company = true, card = true)
    @PostMapping("getCompany")
    public ResultModel<CompanyDetailResponse> getCompany() {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        Company company = companyBaseService.getById(userCompanyId);
        CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(userCompanyId);
        CompanyDetailResponse response1 = CompanyDetailResponse.builder()
                .companyName(company.getCompanyName())
                .companyNotice(company.getCompanyNotice())
                .industryId(company.getIndustryId())
                .companyLogo(company.getCompanyLogo())
                .password(company.getPassword())
                .addrArea(company.getAddrArea())
                .addrStreet(company.getAddrStreet())
                .addrNo(company.getAddrNo())
                .showRoomState(company.getShowroomstate())
                .showRoomUrl(companyShowroom == null ? "" : companyShowroom.getVrUrl())
                .build();
        return ResultModel.success(response1);
    }

    @ApiOperation("行业列表")
    @GetMapping("getList")
    public ResultModel<List<IndustryResponse>> getList() {
        return crmFegin.getList();
    }

    @ApiOperation(value = "修改企业")
    @PostMapping("updCompany")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<Boolean> updCompany(@RequestAttribute com.jmp.api.crm.dto.CompanyEditRequest request) {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        CompanyEditRequest companyEditRequest = CompanyEditRequest.builder()
                .companyId(userCompanyId)
                .companyLogo(request.getCompanyLogo())
                .companyName(request.getCompanyName())
                .password(request.getPassword())
                .industryId(request.getIndustryId())
                .companyNotice(request.getCompanyNotice())
                .phone(request.getPhone())
                .addrArea(request.getAddrArea())
                .addrStreet(request.getAddrStreet())
                .addrNo(request.getAddrNo())
                .build();
        ResultModel resultModel = companyFeign.edit(companyEditRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success(true);
    }

    @ApiOperation(value = "crmPC-支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantId", value = "商户id", required = true, paramType = "String"),
            @ApiImplicitParam(name = "key", value = "秘钥", required = true, paramType = "String"),
            @ApiImplicitParam(name = "certData", value = "文件", required = true, paramType = "String"),
    })
    @PostMapping("payment")
    @SecurityAuthCheck(company = true)
    public ResultModel<String> payment(@RequestAttribute CompanyAccountRequest request) {
        return crmFegin.payment(request);
    }

    @RequestMapping(value = "/backPayMent")
    public String backPayMent(HttpServletRequest request) {
        try {
            BufferedReader reader = request.getReader();
            String line = "";
            StringBuffer inputString = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            request.getReader().close();
            return crmFegin.backPayMent(inputString.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fail();
    }

    /**
     * 企业移交
     */
    @ApiOperation(value = "crmPC-企业转移")
    @PostMapping("companyTransfer")
    @SecurityAuthCheck(company = true, card = true, isBoss = true)
    public ResultModel companyTransfer(@RequestAttribute CompanyTransferRequest request) {
        if (request.getUserId() == null) {
            return ResultModel.fail("移交用户不能为空");
        }
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();

        ResultModel resultModel = companyFeign.transfer(CompanyTransferRequest.builder()
                .userId(request.getUserId())
                .companyId(userCompanyId)
                .build());
        AssertUtil.isTrue(resultModel);
        return ResultModel.success();
    }

    @PostMapping("dissolution")
    @ApiOperation(value = "解散企业")
    @SecurityAuthCheck(company = true, card = true, isBoss = true)
    public ResultModel dissolution() {
        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        CompanyDissolutionRequest companyDissolutionRequest = CompanyDissolutionRequest.builder()
                .companyId(user.getCompanyId())
                .build();
        ResultModel resultModel = companyFeign.dissolution(companyDissolutionRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    public String fail() {
        return "<xml> \n" +
                "  <return_code><![CDATA[fail]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }
}
